var chat = require('./chat');

class wsSocket {
    url = '';token = '';client_id = '';ws ={};chat_user;
    constructor(url, ChatList) {
        this.url = url;
        this.ChatList = ChatList;
        this.chat_user = undefined;
        if ($('#ChatUserId').text() === undefined) {
            throw new Error('do not have token');
        } else {
            this.token = $('#ChatUserId').text();
        }
    }

    connect()
    {
        if ('WebSocket' in window) {
            this.ws = new WebSocket(this.url);
            var that = this;
            this.ws.onopen = function (t) {
                that.log('Connection open');
            }

            this.ws.onmessage = function (t) {
                var res = JSON.parse(t.data);
                switch (res.data.type) {
                    case 'init':
                        that.log('收到 init响应:');
                        that.client_id = res.client_id;
                        myWs.login();
                        break;
                    case 'login':
                        that.log('收到 login 响应');
                        that.chat_user = res.data.data;
                        myWs.send('group_list', {"limit":10, "page":1});
                        break;
                    case 'group_message_record':
                        that.log('收到 group_message_record 响应');
                        that.group_message_record(res.data);
                        break;
                    case 'group_list':
                        that.log('收到 group_list 响应');
                        that.group_list(res.data.data);
                        break;
                    case 'group_send_msg':
                        that.group_send_msg(res.data.data);
                        break;
                    case 'close':
                        that.log('收到 close 响应');
                        that.log(res);
                        break;
                    case 'ping':
                        that.log('收到 ping 响应');
                        that.ping();
                        break;
                }
            }

        } else {
            this.log('This Browser does not support WebSock tool');
        }
    }

    group_list(data)
    {
        var that = this;
        var list = new this.ChatList(this.chat_user.id);

        var arr = [];
        var last = [];
        data.message.forEach(function (e) {
            last[e.chat_group_id] = {
                "content":e.content,
                "type":e.type,
            };
        });
        data.list.forEach(function (e) {
            // console.log('inviter_id:', e.inviter_id, ' user_id:', that.chat_user.id);
            if (e.inviter_id != that.chat_user.id) {
                arr.push({
                    "id":e.id,
                    "avatar":e.inviter.related_table.avatar,
                    "nickname":e.inviter.related_table.name,
                    "last":last[e.id],
                });
            } else {
                arr.push({
                    "id":e.id,
                    "avatar":e.invitee.related_table.avatar,
                    "nickname":e.invitee.related_table.name,
                    "last":last[e.id],
                });
            }
        });
        var htmls = list.initList(arr);
        document.getElementById('list').innerHTML = htmls;
    }

    log(value)
    {
        if (true) {
         console.log(value);
        }
    }

    login()
    {
        var arr = {};
        this.send('bind', arr);
    }

    ping()
    {
        this.send('ping');
    }

    send(type,data)
    {
        if (type === 'ping') {
            this.log('响应心跳:'+JSON.stringify({"type": "ping"}));
            this.ws.send(JSON.stringify({"type": "ping"}));
        } else {
            var arr = {
                "token" : this.token,
                "type": type,
                "data" : data,
            };
            this.log(type + ' send data: ' + JSON.stringify(arr));
            this.ws.send(JSON.stringify(arr));
        }
    }

    // 切换聊天对象
    change_chat_box(data)
    {

    }

    // 消息记录
    group_message_record(data)
    {
        if (this.chat_user === undefined) {
            throw new Error('undefined attr');
        }
        var chatMessageObj = new chat.ChatMessage(this.chat_user.id);
        // 判断聊天框是否为空
        if (!$('.msg-more').length) {
            var html = chatMessageObj.init(data.data.message);
        } else {
            var html = chatMessageObj.append(data.data.message);
        }

        $('#messages-list').innerHTML = html;
    }

    // 近期消息
    group_message_new(data)
    {

    }

    // 发送消息
    group_send_msg(data)
    {
        if (data === undefined || data.length < 1) {
            // 发送失败
        } else {
            // 发送成功
            var obj = new chat.ChatMessage(this.chat_user.id);
            var id = [];
            var user = data.user_data;
            user.forEach(function (e) {
                usr_arr = {"avatar":e.related_table.avatar, "nickname": e.related_table.nickname};
                id[e.id] = usr_arr;
            });
            var data_group_id = data.message[0].chat_group_id;
            data.message.forEach(function (e) {
                e.avatar = id[e.chat_user_id].avatar;
                e.nickname = id[e.chat_user_id].nickname;
            });
            // 正在当前聊天窗口才更新窗口视图，否则只更新好友列表视图
            var active = $('div .active').attr('data-group-id');
            if (data_group_id == active) {
                // 更新视图
                var html = obj.append(data.message);
                document.getElementById('messages-list').innerHTML += html;
                var item = "div[data-group-id="+data_group_id+"]:first";
                var last = $(item).find('.last-message');
                // console.log('last:', last, "item:", item);
                last[0].innerText = data.message[0].content;
            } else  {
                var last = $("div[data-group-id="+data_group_id+"]").children('.name-container').children('.last-message');
                last[0].innerText = data.message[0].content;
                // 标记红点
                $("div[data-group-id="+data_group_id+"]")[0].innerHTML += '<div class="red-dot-notify"></div>';
            }
        }
    }

    // 重新发送
    group_send_msg_rep(data)
    {
        
    }
}

module.exports = {
    create:wsSocket,
};